package com.example.codefilter.project.sys.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @version 1.0.0
 * @className: ValidateController
 * @description: 获取验证码
 * @author: LiJunYi
 * @create: 2022/7/27 9:49
 */
@Controller
public class ValidateController
{
    @Resource
    private Producer captchaProducer;

    @GetMapping("/captchaCode")
    public void  createImgCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 生成图形校验码内容
        String text = captchaProducer.createText();
        // 将验证码内容存入HttpSession
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        // 将验证码有效期存入HttpSession，60秒有效
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_DATE, LocalDateTime.now().plusSeconds(60));
        // 生成图形校验码图片
        BufferedImage bufferedImage = captchaProducer.createImage(text);
        // 将校验码图片信息输出到浏览器
        ImageIO.write(bufferedImage, "jpeg", response.getOutputStream());
    }
}
